package com.haizhi.crm.sys.auth.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yangyijun on 2018/5/16.
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DepartmentVo {
    private Long id;
    private String name;
    private String directSuperiorDept;
    private List<DepartmentVo> children = new ArrayList<>();

    public DepartmentVo(Long id, String name, String directSuperiorDept) {
        this.id = id;
        this.name = name;
        this.directSuperiorDept = directSuperiorDept;
    }

    public void addChildren(DepartmentVo departmentVo) {
        children.add(departmentVo);
    }

    public static List<DepartmentVo> buildTree(List<DepartmentVo> deptVos) {
        List<DepartmentVo> rootDept = new ArrayList<>();
        Map<Long, DepartmentVo> dMap = new HashMap<>();
        for (DepartmentVo dv : deptVos) {
            if (dv.getDirectSuperiorDept() == null) {
                rootDept.add(dv);
            }
            dMap.put(dv.getId(), dv);
        }

        for (DepartmentVo dv : deptVos) {
            String parents = dv.getDirectSuperiorDept();
            if (parents != null) {
                String[] parentIds = parents.split("," );
                for (String parentId : parentIds) {
                    if (dMap.containsKey(parentId)) {
                        dMap.get(parentId).addChildren(dv);
                    }
                }

            }
        }
        return rootDept;
    }
}
